package fr.univ.lille1.server.managerimpl;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import fr.univ.lille1.server.dao.SessionKeyDao;
import fr.univ.lille1.server.domain.SessionKey;
import fr.univ.lille1.server.domain.User;
import fr.univ.lille1.server.manager.SessionKeyManager;

@Stateless
public class SessionKeyManagerImpl implements SessionKeyManager {

	@EJB
	private SessionKeyDao sessionKeyDao;

	@Override
	public SessionKey generateNewKey(User user) {
		return sessionKeyDao.generateNewKey(user);
	}

	@Override
	public boolean correctSessionKey(String clientKey, User user) {
		SessionKey session = this.findSessionKeyByUserId(user.getId());

		if (!session.getSessionKey().equals(clientKey) || clientKey.equals("")) {
			return false;
		}

		long timeKey = session.getGenerateTime();
		long currentTime = System.currentTimeMillis();
		if ((currentTime - timeKey) / 1000 >= (3600*30)) {
			//  clé valable pour 1 mois
			return false;
		}

		return true;
	}

	@Override
	public SessionKey findSessionKeyByUserId(int id) {
		return sessionKeyDao.find(id);
	}

	@Override
	public SessionKey createSessionKey(User user, String sessionKey,long generateTime) {
		SessionKey session = new SessionKey(user, sessionKey,generateTime);
		return sessionKeyDao.create(session);
	}

	@Override
	public SessionKey updateSessionKey(SessionKey sessionKey) {
		return sessionKeyDao.update(sessionKey);
	}
}
